Collection Initializers in C#

As the C # 3.0 provides a new way of initializing objects, a new syntax is included to prepare a list with a particular set object. We can use the car class from the last chapter:

class Car
{
    public string Name { get; set; }
    public Color Color { get; set; }
}

If we want to create a list to include many cars, then we have to do something similar with C # 2.0:

Car car;
List<Car> cars = new List<Car>();

car = new Car();
car.Name = "Corvette";
car.Color = Color.Yellow;
cars.Add(car);

car = new Car();
car.Name = "Golf";
car.Color = Color.Blue;
cars.Add(car);

Using object initializers, we could do it a bit shorter:

List<Car> cars = new List<Car>();
cars.Add(new Car { Name = "Corvette", Color = Color.Yellow });
cars.Add(new Car { Name = "Golf", Color = Color.Blue});

However, it can be even simpler, when combined with collection initializers:

List<Car> cars = new List<Car> 
{ 
    new Car { Name = "Corvette", Color = Color.Yellow },
    new Car { Name = "Golf", Color = Color.Blue}
};

Or in the one-line version, which does exactly the same:

List<Car> cars = new List<Car> { new Car { Name = "Corvette", Color = Color.Yellow }, new Car { Name = "Golf", Color = Color.Blue} };

10 lines of code has been reduced to a single, albeit a bit long, line, thanks to object and collection initializers.